package com.zj.osm.view.project.projectdetail.fragment;

import android.annotation.SuppressLint;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;

import com.bin.david.form.core.SmartTable;
import com.blankj.utilcode.util.ToastUtils;
import com.zj.osm.App;
import com.zj.osm.R;
import com.zj.osm.bean.BomBean;
import com.zj.osm.bean.MaterialsProject;
import com.zj.osm.bean.PointLineModuleBean;
import com.zj.osm.entity.db.EquipmentDao;
import com.zj.osm.entity.db.LineDao;
import com.zj.osm.entity.db.PointDao;
import com.zj.osm.entity.db.ProjectDao;
import com.zj.osm.entity.greendao.Equipment;
import com.zj.osm.entity.greendao.Line;
import com.zj.osm.entity.greendao.Point;
import com.zj.osm.entity.greendao.Project;
import com.zj.osm.utils.ExcelUtil;
import com.zj.osm.utils.SQLiteDatabaseUtils;
import com.zj.osm.view.BaseFragment;
import com.zj.osm.view.project.projectdetail.ProjectDetailActivity;
import com.zj.utils.utils.ShareUtils;

import java.io.File;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import static com.zj.utils.utils.MathUtils.eval;


/**
 * 物料清单
 */
public class MaterialFragment extends BaseFragment implements View.OnClickListener {
    private List<BomBean> bomBeanresult = new ArrayList<>();
    List<String> danweiData = new ArrayList<>();
    List<Line> line;
    //所有点的moudle的ID
    List<PointLineModuleBean> moudleIDList = new ArrayList<>();
    NumberFormat nf = NumberFormat.getNumberInstance();
    private SmartTable materialSmartTable;
    private ImageButton detailsBtnBack;
    private TextView detailsTvOne;
    private TextView detailsTvTwo;
    private Button detailsBtnJc;
    private Button detailsBtnKcxx;
    private Button detailsBtnWlqd;
    private Button detailsBtnGdfa;
    private Set<Line> lineSet = new HashSet<Line>();


    @Override
    protected int getContentViewLayoutID() {
        return R.layout.fragment_material;
    }

    protected void initView(View view) {
        danweiData.add("只");
        danweiData.add("套");
        danweiData.add("副");
        danweiData.add("付");
        danweiData.add("片");
        danweiData.add("个");
        danweiData.add("米");
        nf.setMaximumFractionDigits(3);
        materialSmartTable = view.findViewById(R.id.materialSmartTable);
        Cursor cursor = App.getInstances().getDaoSession().getDatabase().rawQuery("SELECT ep.* from EQUIPMENT ep left join Point p on ep.POINT_ID = p._id where p.PROJECT_ID =? and p.STATE in ('新建','改造')", new String[]{ProjectDetailActivity.PROJECT_DETAILS_ID + ""});
        List<Point>allPoint=App.getInstances().getDaoSession().getPointDao().queryBuilder().where(PointDao.Properties.ProjectId.eq(ProjectDetailActivity.PROJECT_DETAILS_ID + "")).list();
        while (cursor.moveToNext()) {
            PointLineModuleBean pointLineModuleBean = new PointLineModuleBean();
            pointLineModuleBean.setMODULE_ID(cursor.getString(cursor.getColumnIndex("MODULE_ID")));
            pointLineModuleBean.setLENGTH("1");
            //会路数
            pointLineModuleBean.setH("1");
            //根数
            pointLineModuleBean.setG("1");
            pointLineModuleBean.setAmount(cursor.getString(cursor.getColumnIndex("AMOUNT")));
            moudleIDList.add(pointLineModuleBean);
        }
        //TODO 1.查所有的线然后进行
        line = App.getInstances().getDaoSession().getLineDao().queryBuilder().where(LineDao.Properties.Item_id.eq(ProjectDetailActivity.PROJECT_DETAILS_ID), LineDao.Properties.State.in("新建", "改造")).build().list();
        Set<Line> allLine = new HashSet<>();
        for (Line line : line) {
            List<Equipment> equipmentList = App.getInstances().getDaoSession().getEquipmentDao().queryBuilder().where(EquipmentDao.Properties.ProjectId.eq(ProjectDetailActivity.PROJECT_DETAILS_ID),EquipmentDao.Properties.Qubie.eq("1"), EquipmentDao.Properties.LineId.eq(line.getId())).build().list();

            Log.e("length=", line.getLength());
            if (allLine.contains(line))
                continue;
            PointLineModuleBean pointLineModuleBean = new PointLineModuleBean();
            pointLineModuleBean.setMODULE_ID(line.getModuleID());
            //会路数
            pointLineModuleBean.setH(line.getBackNum());
            //根数
            pointLineModuleBean.setG(line.getNum());
            pointLineModuleBean.setAmount("1");

            lineSet.clear();
            Set<Line> subLine = getRelationLine(line);
            allLine.addAll(subLine);
            double length = 0.0;
            for (Line l : subLine) {
                length += Double.parseDouble(l.getLength()) / 1000;
            }
            pointLineModuleBean.setLENGTH(length + "");
            moudleIDList.add(pointLineModuleBean);

            if (equipmentList.size() > 0) {
                for (int i = 0; i < equipmentList.size(); i++) {
                    PointLineModuleBean pointLineModuleBeans = new PointLineModuleBean();
                    pointLineModuleBeans.setMODULE_ID(equipmentList.get(i).getLever_id() + "");
                    //会路数
                    pointLineModuleBeans.setH(line.getBackNum());
                    //根数
                    pointLineModuleBeans.setG(line.getNum());
                    pointLineModuleBeans.setAmount("1");
                    pointLineModuleBeans.setLENGTH(length + "");
                    moudleIDList.add(pointLineModuleBeans);
                }
            }
        }
        //TODO 2.0去进循环
        List<MaterialsProject> xiaojiangjiang = getWuliaoResultList(moudleIDList);
        for (int i = 0; i < xiaojiangjiang.size(); i++) {
            BomBean bomBean = new BomBean();
            bomBean.setMaterialsProjectID(xiaojiangjiang.get(i).getMaterialsProjectID());
            bomBean.setMaterialCodeERP(xiaojiangjiang.get(i).getMaterialCodeERP());
            bomBean.setMaterialName(xiaojiangjiang.get(i).getMaterialName());
            bomBean.setSpec(xiaojiangjiang.get(i).getSpec());
            bomBean.setERPUnit(xiaojiangjiang.get(i).getDesignUnit());
            //TODO 这里搞数据计算
            bomBean.setTechnicalProtocol(xiaojiangjiang.get(i).getTechnicalProtocol());
            //TODO 类型
            // bomBean.setBomType("类型");
            bomBean.setNum(xiaojiangjiang.get(i).getWuliaoFormnue());
            if (xiaojiangjiang.get(i).getMaterialName() != null && !xiaojiangjiang.get(i).getMaterialName().equals(""))
                bomBeanresult.add(bomBean);
        }
        materialSmartTable.setData(bomBeanresult);
        cursor.close();
        detailsBtnBack = view.findViewById(R.id.detailsBtnBack);
        detailsBtnBack.setOnClickListener(this);
        detailsTvOne = view.findViewById(R.id.detailsTvOne);
        detailsTvOne.setOnClickListener(this);
        detailsTvTwo = view.findViewById(R.id.detailsTvTwo);
        detailsTvTwo.setOnClickListener(this);
        detailsBtnJc = view.findViewById(R.id.detailsBtnJc);
        detailsBtnJc.setOnClickListener(this);
        detailsBtnKcxx = view.findViewById(R.id.detailsBtnKcxx);
        detailsBtnKcxx.setOnClickListener(this);
        detailsBtnWlqd = view.findViewById(R.id.detailsBtnWlqd);
        detailsBtnWlqd.setOnClickListener(this);
        detailsBtnGdfa = view.findViewById(R.id.detailsBtnGdfa);
        detailsBtnGdfa.setOnClickListener(this);
        detailsBtnJc.setBackgroundResource(R.drawable.btn_shape_white);
        detailsBtnKcxx.setBackgroundResource(R.drawable.btn_shape_white);
        detailsBtnWlqd.setBackgroundResource(R.drawable.btn_shape);
        detailsBtnGdfa.setBackgroundResource(R.drawable.btn_shape_white);
        //detailsTvOne.setText("保存");
        detailsTvTwo.setText("导出");
        detailsBtnJc.setTextColor(Color.rgb(51, 51, 51));
        detailsBtnKcxx.setTextColor(Color.rgb(51, 51, 51));
        detailsBtnWlqd.setTextColor(Color.rgb(255, 255, 255));
        detailsBtnGdfa.setTextColor(Color.rgb(51, 51, 51));
        new BasisFragment().clickItem(this, detailsBtnBack, detailsBtnJc, detailsBtnKcxx, detailsBtnWlqd, detailsBtnGdfa);
    }

    /**
     * 生成和导出Excel文件
     *
     * @param flag /
     */
    public void export(int flag) {
        Project items = App.getInstances().getDaoSession().getProjectDao().queryBuilder().where(ProjectDao.Properties.Id.eq(ProjectDetailActivity.PROJECT_DETAILS_ID)).list().get(0);
        String excelName = items.getName();
        String filePath = Environment.getExternalStorageDirectory().getAbsolutePath()
                + "/bhne/";
        File files = new File(filePath);
        if (!files.exists()) {
            files.mkdirs();
        }
        String[] title = {"物料ID", "物料编码", "物料名称", "规格型号", "单位", "数量", "技术协议"};
        String excelFileName = "/" + excelName + ".xls";
        String resultPath = files.getAbsolutePath() + excelFileName;
        Log.e("rultPath", resultPath);
        ExcelUtil.initExcel(excelName, resultPath, title);
        File moudleFile = ExcelUtil.writeObjListToExcel(bomBeanresult, resultPath, getContext());
        if (flag == 0) {
            if (moudleFile != null) {
                ToastUtils.showShort("已经保存到本地" + filePath);
            }
        } else {
            ShareUtils.shareFile(getActivity(), moudleFile);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.detailsTvOne://保存
                export(0);
                break;
            case R.id.detailsTvTwo://导出
                export(1);
                break;
        }
    }
    private Set<Line> getRelationLine(Line line) {
        lineSet.add(line);
        Log.e("line", line.toString());
        List<Point> pointlst = App.getInstances().getDaoSession().getPointDao().queryBuilder().whereOr(PointDao.Properties.ProjectId.eq(ProjectDetailActivity.PROJECT_DETAILS_ID),PointDao.Properties.Uid.eq(line.getStart_id()), PointDao.Properties.Uid.eq(line.getEnd_id())).build().list();
        for (Point p : pointlst) {
            if (p.getName().contains("拐点")) {
                List<Line> lines = App.getInstances().getDaoSession().getLineDao().queryBuilder().whereOr(LineDao.Properties.Item_id.eq(ProjectDetailActivity.PROJECT_DETAILS_ID),LineDao.Properties.Start_id.eq(p.getUid()), LineDao.Properties.End_id.eq(p.getUid())).build().list();
                for (Line l : lines) {
                    if (!lineSet.contains(l)) {
                        getRelationLine(l);
                    }
                }
            }
        }
        return lineSet;
    }
    @Override
    public void initListener() {

    }
    private String getNumber(String NUMBER, String LENGTH, String AMOUNT, String H, String G) {
        Log.e("getNumber===","number="+NUMBER+"length="+LENGTH+"Amoount=="+AMOUNT+"H=="+H+"G=="+G);
        String replaceResult = (NUMBER + "*" + AMOUNT).replace("L", LENGTH+"*1000").replace("H", H).replace("G", G);
        Log.e("replaceGS=", replaceResult);
        NumberFormat nf = NumberFormat.getNumberInstance();
        nf.setMaximumFractionDigits(3);
        Log.e("reslsfjl=", eval(replaceResult) + "");
        return (double) Math.round(eval(replaceResult) * 1000) / 1000 + "";
    }

    private List<MaterialsProject> getWuliaoResultList(List<PointLineModuleBean> moudleIDList) {
        List<MaterialsProject> strings = new ArrayList<>();
        List<String> proJectModuleId = new ArrayList<>();

        SQLiteDatabase db = SQLiteDatabaseUtils.getInstance().getSQLiteDatabase();
        assert db != null;
        for (int i = 0; i < moudleIDList.size(); i++) {
            if (moudleIDList.get(i).getMODULE_ID() != null && !moudleIDList.get(i).getMODULE_ID().equals("")) {
                Log.e("sqlresult=","select mp.MaterialsProjectID,mp.MaterialName,mp.MaterialsTypeKey,mp.MaterialCodeERP,mp.Spec,mp.Voltage,mp.IsMain,mp.IsLine,mp.DesignUnit,mp.ERPUnit,mp.Ratio,mp.Weight,mp.TechnicalProtocol,mp.FLag,mp.ISDonor,mm.num," + moudleIDList.get(i).getLENGTH() + " as length," + moudleIDList.get(i).getAmount() + " as amount from ModuleMaterials mm left join MaterialsProject mp on  mm.MaterialsProjectID = mp.MaterialsProjectID where mm.ModuleID=" + moudleIDList.get(i).getMODULE_ID()+"");
                Log.e("squl", "select mp.*,mm.num," + moudleIDList.get(i).getLENGTH() + " as length," + moudleIDList.get(i).getAmount() + " as amount from ModuleMaterials mm left join MaterialsProject mp on  mm.MaterialsProjectID = mp.MaterialsProjectID where mm.ModuleID=" + moudleIDList.get(i).getMODULE_ID());
                @SuppressLint("Recycle")
                Cursor cursor = db.rawQuery("select mp.MaterialsProjectID,mp.MaterialName,mp.MaterialsTypeKey,mp.MaterialCodeERP,mp.Spec,mp.Voltage,mp.IsMain,mp.IsLine,mp.DesignUnit,mp.ERPUnit,mp.Ratio,mp.Weight,mp.TechnicalProtocol,mp.FLag,mp.ISDonor,mm.num," + moudleIDList.get(i).getLENGTH() + " as length," + moudleIDList.get(i).getAmount() + " as amount from ModuleMaterials mm left join MaterialsProject mp on  mm.MaterialsProjectID = mp.MaterialsProjectID where mm.ModuleID=" + moudleIDList.get(i).getMODULE_ID(), null);//此处的db是表名，name是列名
                while (cursor.moveToNext()) {
                    if (!proJectModuleId.contains(cursor.getString(0))) {
                        proJectModuleId.add(cursor.getString(0));
                        MaterialsProject modelType = new MaterialsProject();
                        modelType.setMaterialsProjectID(cursor.getString(0));
                        modelType.setMaterialName(cursor.getString(1));
                        modelType.setMaterialsTypeKey(cursor.getString(2));
                        modelType.setMaterialCodeERP(cursor.getString(3));
                        modelType.setSpec(cursor.getString(4));
                        modelType.setVoltage(cursor.getString(5));
                        modelType.setIsMain(cursor.getString(6));
                        modelType.setIsLine(cursor.getString(7));
                        modelType.setDesignUnit(cursor.getString(8));
                        modelType.setERPUnit(cursor.getString(9));
                        modelType.setRatio(cursor.getString(10));
                        modelType.setWeight(cursor.getString(11));
                        modelType.setTechnicalProtocol(cursor.getString(12));
                        modelType.setFLAG(cursor.getString(13));
                        modelType.setIsDonor(cursor.getString(14));
                        if (danweiData.contains(cursor.getString(9))) {
                            if (cursor.getString(9).equals("米")) {
                                if(cursor.getString(15)!=null&&cursor.getString(16)!=null&&cursor.getString(17)!=null) {
                                    modelType.setWuliaoFormnue(Double.parseDouble(getNumber(cursor.getString(15).trim(), cursor.getString(16).trim(), cursor.getString(17).trim(), moudleIDList.get(i).getH(), moudleIDList.get(i).getG())) + "");
                                }
                            } else {
                                if(cursor.getString(15)!=null&&cursor.getString(16)!=null&&cursor.getString(17)!=null) {

                                    modelType.setWuliaoFormnue(((int) Math.round(Double.parseDouble(getNumber(cursor.getString(15).trim(), cursor.getString(16).trim(), cursor.getString(17).trim(), moudleIDList.get(i).getH(), moudleIDList.get(i).getG())))) + "");
                                }
                            }
                        } else {
                            if(cursor.getString(15)!=null&&cursor.getString(16)!=null&&cursor.getString(17)!=null) {
                                String number = getNumber(cursor.getString(15).trim(), cursor.getString(16).trim(), cursor.getString(17).trim(), moudleIDList.get(i).getH(), moudleIDList.get(i).getG());
                                modelType.setWuliaoFormnue(number);
                            }


                        }
                        strings.add(modelType);
                    } else {
                        MaterialsProject materialsProject = strings.get(proJectModuleId.indexOf(cursor.getString(0)));
                        if(cursor.getString(15)!=null&&cursor.getString(16)!=null&&cursor.getString(17)!=null) {
                            Log.e("getNumber111111===","number="+cursor.getString(15).trim()+"length="+cursor.getString(16).trim()+"Amoount=="+cursor.getString(17).trim()+"H=="+moudleIDList.get(i).getH()+"G=="+ moudleIDList.get(i).getG());
                            String resultgongshi = materialsProject.getWuliaoFormnue() + "+" + getNumber(cursor.getString(15).trim(), cursor.getString(16).trim(), cursor.getString(17).trim(), moudleIDList.get(i).getH(), moudleIDList.get(i).getG());
                            Log.e("alllreisll==",resultgongshi);
                            if (danweiData.contains(cursor.getString(9))) {
                                materialsProject.setWuliaoFormnue(((int) Math.round(eval(resultgongshi))) + "");
                            } else {
                                materialsProject.setWuliaoFormnue(nf.format(eval(resultgongshi)));

                            }
                        }

                    }
                }
                cursor.close();

            }
        }
        return strings;
    }
}
